/*
 * -------------------------------------------------------------------------
 * 主窗口管理
 * -------------------------------------------------------------------------
 */

/*app对象实例*/
let app;
const path          = require('path');
const electron      = require('electron');
const setting       = require('../setting');
const renderSetting = require('../render/setting');
const is            = require('../../helper/is');
const configs       = require('../../package.json').configs;
const BrowserWindow = electron.BrowserWindow;

/**
 * 初始化
 * @param appInstance
 */
function initialize (appInstance) {
    /*复写app实例*/
    app = appInstance;
    
    /*设置的透明度*/
    let Setting = setting.read();
    
    /*初始化*/
    app.$windowMain = new BrowserWindow({
        width          : Setting.width || configs.windowMain.minWidth,
        height         : Setting.height || configs.windowMain.minHeight,
        minWidth       : configs.windowMain.minWidth,
        minHeight      : configs.windowMain.minHeight,
        x              : Setting.x || null,
        y              : Setting.y || null,
        frame          : false,
        show           : false, /*默认不显示*/
        transparent    : false,
        maximizable    : true,
        backgroundColor: '#111',
        opacity        : Setting.opacity ? (Setting.opacity / 100) : 1,
        icon           : path.resolve(__dirname, `../../${configs.icon.normal}`),
        webPreferences : {
            defaultEncoding        : 'UTF-8',
            contextIsolation       : false,
            spellcheck             : false, /* 是否启用内置拼写检查器 */
            nodeIntegration        : true,
            nodeIntegrationInWorker: true,
            plugins                : true,
            webviewTag             : true,
            preload                : path.resolve(__dirname, '../../src/render/inject.js')
        }
    });
    
    /*windowMain引用*/
    let win = app.$windowMain;
    
    /*开发模式*/
    if (is.electronDev()) {
        win.loadURL(`http://${configs.develop.host}:${configs.develop.port}`).then(() => {});
        win.openDevTools();
    }
    /*打包模式*/
    else {
        win.loadURL(path.resolve(__dirname, '../..', configs.production.buildDir, configs.production.indexFile)).then(() => {});
    }
    
    /*加载完成后显示窗口*/
    win.on('ready-to-show', win.show);
    
    /*渲染进程加载完毕*/
    win.webContents.on('dom-ready', renderSetting.rendererNotify);
    
    /*移动窗时记录坐标*/
    win.on('moved', () => setting.update((([x, y] = win.getPosition()) => ({ x, y }))()));
    
    /*改变窗口尺寸时记录尺寸*/
    win.on('resized', () => setting.update((([width, height] = win.getSize()) => ({ width, height }))()));
}

/**
 * 导出
 * @type {{initialize: initialize}}
 */
module.exports = {
    initialize
};
